package com.meiyu.live.widget;

import android.app.Dialog;
import android.content.Context;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.meiyu.live.BaseActivity;
import com.meiyu.live.R;
import com.meiyu.live.eventbus.FocusEvent;
import com.meiyu.live.net.param.IsfocusParams;
import com.meiyu.live.net.param.PersonalParams;
import com.meiyu.live.net.response.BaseResponse;
import com.meiyu.live.net.response.PersonalResponse;
import com.meiyu.live.popj.PersonalInfo;
import com.meiyu.live.popj.RelationInfo;
import com.meiyu.live.util.ToastUtil;

import java.text.DecimalFormat;

import de.greenrobot.event.EventBus;


/**
 * 用户信息对话框
 */
public class UserInfoDialog extends Dialog implements View.OnClickListener {

    private Context context;
    private ImageLoader imageLoader;
    private DisplayImageOptions options;

    private View btn_close;
    private TextView btn_follow, btn_privatemessage;
    private ImageView iv_avatar, iv_sex;
    private TextView tv_nickname, tv_level, tv_account, tv_location, tv_signature;
    private TextView tv_follow_count, tv_fans_count, tv_receive_count, tv_send_count;
    private View layout_follow_count, layout_fans_count, layout_receive_count, layout_send_count, layout_bottom_btn;

    private PersonalResponse personalResponse;
    private long userId;
    private String neteaseId;

    private boolean isFollow;
    private boolean isGetData = true;

    public interface UserInfoListener {
        void onClickFollow();

        void onClickPrivateMessage(String neteaseId);
    }

    private UserInfoListener userInfoListener;

    public UserInfoDialog(Context context) {
        super(context, R.style.dialog_custom);
        init(context);
    }

    public UserInfoDialog(Context context, int theme) {
        super(context, theme);
        init(context);
    }

    private void init(Context context) {
        this.context = context;
        setContentView(R.layout.dialog_userinfo);
        setCanceledOnTouchOutside(false);
        imageLoader = ImageLoader.getInstance();
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.icon_def_header)          // 设置图片下载期间显示的图片
                .showImageForEmptyUri(R.drawable.icon_def_header)  // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.drawable.icon_def_header)       // 设置图片加载或解码过程中发生错误显示的图片
                .cacheInMemory(true)                        // 设置下载的图片是否缓存在内存中
                .cacheOnDisk(true)                          // 设置下载的图片是否缓存在SD卡中
                .build();

        btn_close = findViewById(R.id.btn_close);
        btn_close.setOnClickListener(this);
        btn_follow = (TextView) findViewById(R.id.btn_follow);
        btn_follow.setOnClickListener(this);
        btn_privatemessage = (TextView) findViewById(R.id.btn_privatemessage);
        btn_privatemessage.setOnClickListener(this);
        iv_avatar = (ImageView) findViewById(R.id.iv_avatar);
        iv_sex = (ImageView) findViewById(R.id.iv_sex);
        tv_nickname = (TextView) findViewById(R.id.tv_nickname);
        tv_level = (TextView) findViewById(R.id.tv_level);
        tv_account = (TextView) findViewById(R.id.tv_account);
        tv_location = (TextView) findViewById(R.id.tv_location);
        tv_signature = (TextView) findViewById(R.id.tv_signature);
        tv_follow_count = (TextView) findViewById(R.id.tv_follow_count);
        tv_fans_count = (TextView) findViewById(R.id.tv_fans_count);
        tv_receive_count = (TextView) findViewById(R.id.tv_receive_count);
        tv_send_count = (TextView) findViewById(R.id.tv_send_count);

        layout_bottom_btn = findViewById(R.id.layout_bottom_btn);
    }

    public void setUserId(String userId) {
        try {
            this.userId = Long.parseLong(userId);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        ((BaseActivity) context).request(new PersonalParams(userId), PersonalResponse.class, new Response.Listener<PersonalResponse>() {
            @Override
            public void onResponse(PersonalResponse personalResponse) {
                if (personalResponse != null) {
                    UserInfoDialog.this.personalResponse = personalResponse;
                    update();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        });
    }


    public void setUserId(String userId, String neteaseId) {
        String id = null;
        if (TextUtils.isEmpty(userId)) {
            if (TextUtils.isEmpty(neteaseId)) {
                return;
            } else {
                id = neteaseId;
            }
        } else {
            id = userId;
        }
        try {
            this.userId = Long.parseLong(userId);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        this.neteaseId = neteaseId;
        ((BaseActivity) context).request(new PersonalParams(id), PersonalResponse.class, new Response.Listener<PersonalResponse>() {
            @Override
            public void onResponse(PersonalResponse personalResponse) {
                if (personalResponse != null) {
                    UserInfoDialog.this.personalResponse = personalResponse;
                    update();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        });
    }

    public void setIsFollow(boolean isFollow) {
        isGetData = false;
        this.isFollow = isFollow;
        btn_follow.setText(isFollow ? "已关注" : "关注");
    }

    public void setUserInfoListener(UserInfoListener userInfoListener) {
        this.userInfoListener = userInfoListener;
        layout_bottom_btn.setVisibility(View.VISIBLE);
    }

    private void update() {
        PersonalInfo personalInfo = personalResponse.getPrivateInfo();
        if (personalInfo != null) {
            imageLoader.displayImage(personalInfo.getAvatar(), iv_avatar, options);
            int sexRes;
            if ("m".equals(personalInfo.getSex())) {
                sexRes = R.drawable.ic_sex_male;
            } else if ("f".equals(personalInfo.getSex())) {
                sexRes = R.drawable.ic_sex_female;
            } else {
                sexRes = R.drawable.ic_sex_secret;
            }
            iv_sex.setImageResource(sexRes);
            tv_nickname.setText(personalInfo.getName());
            tv_account.setText("账号：" + personalInfo.getCuteCode());
            if ("".equals(personalInfo.getAddress()) || "请选择省市".equals(personalInfo.getAddress())) {
                tv_location.setText("火星");
            } else {
                tv_location.setText(personalInfo.getAddress());
            }

            tv_signature.setText("个性签名：" + personalInfo.getSignature());

            setIsFollow(personalResponse.getPrivateInfo().getIsFocus() > 0);
        } else {
            tv_nickname.setText("未知用户");
            tv_account.setText("魅鱼账号：");
            tv_location.setText("未填写家乡信息");
            tv_signature.setText("个性签名：");
        }
        RelationInfo relationInfo = personalResponse.getRelationinfo();
        if (relationInfo != null) {
            tv_level.setText(relationInfo.getLevel() + "");
            tv_follow_count.setText(relationInfo.getFocus() + "");
            tv_fans_count.setText(relationInfo.getFans() + "");
            DecimalFormat df = new DecimalFormat("#.00");
            tv_receive_count.setText(relationInfo.getIncome() / 10000 > 0 ? df.format((float) relationInfo.getIncome() / 10000) + "万" : relationInfo.getIncome() + "");
            tv_send_count.setText(relationInfo.getExpense() / 10000 > 0 ? df.format((float) relationInfo.getExpense() / 10000) + "万" : relationInfo.getExpense() + "");
        } else {
            tv_level.setText("0");
            tv_follow_count.setText("0");
            tv_fans_count.setText("0");
            tv_receive_count.setText("0");
            tv_send_count.setText("0");
        }
    }

    @Override
    public void onClick(View view) {
        if (view == btn_close) {
            dismiss();
        } else if (view == btn_follow) {
            if (isGetData) {
                return;
            } else {
                if (isFollow) {//取消关注
                    int a[] = {0, 1};
                    ((BaseActivity) context).request(new IsfocusParams(userId, a), BaseResponse.class, new Response.Listener<BaseResponse>() {
                        @Override
                        public void onResponse(BaseResponse onlyStatusResponse) {
                            setIsFollow(false);
                            ToastUtil.show("已取消关注");
                            EventBus.getDefault().post(new FocusEvent(false, userId));
                        }
                    });
                } else {//关注
                    int a[] = {1, 1};
                    ((BaseActivity) context).request(new IsfocusParams(userId, a), BaseResponse.class, new Response.Listener<BaseResponse>() {
                        @Override
                        public void onResponse(BaseResponse onlyStatusResponse) {
                            setIsFollow(true);
                            ToastUtil.show("关注成功");
                            EventBus.getDefault().post(new FocusEvent(true, userId));
                        }
                    });
                }
            }

        } else if (view == btn_privatemessage) {
            if (userInfoListener != null) {
                userInfoListener.onClickPrivateMessage(neteaseId);
            }
        }
    }
}
